<template>
  <page-header-wrapper>
    <n-card>
      <div class="table-page-search-wrapper mb-md">
        <n-grid x-gap="24" cols="1 s:1 m:2 l:3 xl:3 2xl:3" responsive="screen">
          <n-gi>
            <div class="flex items-center">
              <label title="编号">编号：</label>
              <div class="flex-1">
                <n-input v-model:value="queryParam.id" type="text" placeholder="请输入编号" />
              </div>
            </div>
          </n-gi>
          <n-gi>
            <div class="flex items-center">
              <label title="年龄">年龄：</label>
              <div class="flex-1">
                <n-input v-model:value="queryParam.age" type="text" placeholder="请输入年龄" />
              </div>
            </div>
          </n-gi>
          <n-gi>
            <div class="flex items-center">
              <n-button type="primary" class="px-lg" @click="query">查询</n-button>
              <n-button class="px-lg ml-sm" @click="reset">重置</n-button>
              <n-button class="px-lg ml-sm" @click="exportXlsx">导出</n-button>
            </div>
          </n-gi>
        </n-grid>
      </div>
      <s-table ref="table" :loadData="loadData" :columns="columns"></s-table>
    </n-card>
  </page-header-wrapper>
  <div></div>
</template>

<script lang="ts">
import { tableList } from '@/api/list'
import { PageHeaderWrapper, STable } from '@/components'
import { LoadDataFunction, STableInstance } from '@/components/STable'
import { TableColumn } from '@/types/naiveui-table'
import { exportData } from '@/utils/xlsx.util'
import { defineComponent, ref } from 'vue'

const columns: TableColumn[] = [
  {
    title: '编号',
    key: 'id'
  },
  {
    title: '姓名',
    key: 'name'
  },
  {
    title: '年龄',
    key: 'age'
  },
  {
    title: '性别',
    key: 'sex'
  }
]

export default defineComponent({
  name: 'TableList',
  components: {
    PageHeaderWrapper,
    STable
  },
  setup() {
    const loadData: LoadDataFunction = async parameter => {
      const res = await tableList({ ...parameter })
      return res.data
    }
    const table = ref<STableInstance>()
    const queryParamInit = {
      id: '',
      age: ''
    }
    const queryParam = ref({ ...queryParamInit })

    const query = () => {
      table.value?.refresh(true)
    }
    // 导出表格数据
    const exportXlsx = async () => {
      const res = await tableList()
      const xlsxDatas = [columns.map(item => item.title)].concat(
        (res.data.data as Record<string, string>[]).map(item => columns.map(column => `${item[column.key] ?? ''}`))
      )
      exportData(xlsxDatas).xslx().save('asd')
    }
    return {
      table,
      queryParam,
      columns,
      loadData,
      query,
      exportXlsx,
      reset: () => {
        queryParam.value = queryParamInit
        query()
      }
    }
  }
})
</script>

<style scoped></style>
